// 这是一个简化的Socket.IO客户端库
// 如果CDN无法访问，这个文件可以作为备用方案

(function() {
    'use strict';
    
    // 简化的Socket.IO客户端实现
    function SocketIO(url, options) {
        this.url = url || window.location.origin;
        this.options = options || {};
        this.connected = false;
        this.events = {};
        this.socket = null;
        
        this.init();
    }
    
    SocketIO.prototype.init = function() {
        try {
            // 使用WebSocket连接
            var wsUrl = this.url.replace(/^http/, 'ws') + '/socket.io/?EIO=4&transport=websocket';
            this.socket = new WebSocket(wsUrl);
            
            var self = this;
            
            this.socket.onopen = function() {
                self.connected = true;
                self.emit('connect');
            };
            
            this.socket.onclose = function() {
                self.connected = false;
                self.emit('disconnect');
            };
            
            this.socket.onmessage = function(event) {
                try {
                    var data = JSON.parse(event.data);
                    if (data.type) {
                        self.emit(data.type, data.data);
                    }
                } catch (e) {
                    console.warn('无法解析Socket.IO消息:', event.data);
                }
            };
            
            this.socket.onerror = function(error) {
                console.error('Socket.IO连接错误:', error);
                self.emit('error', error);
            };
            
        } catch (error) {
            console.error('Socket.IO初始化失败:', error);
        }
    };
    
    SocketIO.prototype.on = function(event, callback) {
        if (!this.events[event]) {
            this.events[event] = [];
        }
        this.events[event].push(callback);
    };
    
    SocketIO.prototype.emit = function(event, data) {
        if (this.events[event]) {
            this.events[event].forEach(function(callback) {
                callback(data);
            });
        }
    };
    
    SocketIO.prototype.send = function(data) {
        if (this.socket && this.connected) {
            this.socket.send(JSON.stringify(data));
        }
    };
    
    // 全局io函数
    window.io = function(url, options) {
        return new SocketIO(url, options);
    };
    
    console.log('本地Socket.IO库已加载');
})();
